"""
    Contains file-storage class implementation.
"""

import os, os.path, glob
import turbogears
from mnemoply.utils import read_file
from mnemoply.model.hub import __connection__

class File(object):
    """
        File object for getting report templates by tag.
    """

    def __init__(self, name):
        self.name = name

    def getLocation(self):
        return os.path.join(self.getFilesDir(), self.name)

    location = property(getLocation)
    tag = property(lambda self: read_file(self.location + ".tag"))
    content = property(lambda self: read_file(self.location))
    exists = property(lambda self: os.access(self.location, os.R_OK))

    @classmethod
    def getFilesDir(cls):
        return turbogears.config.get("files.dir")

    @classmethod
    def byTag(cls, required_tag):
        tag_files = glob.glob(os.path.join(cls.getFilesDir(), '*.tag'))

        for tag_file in tag_files:
            tag = read_file(tag_file).strip()

            if tag == required_tag:
                return cls(os.path.basename(tag_file)[:-4])

        raise KeyError("Tag %s not found" % required_tag)

